package cn.tedu.passort.service.impl;

import cn.tedu.common.enumerator.ServiceCode;
import cn.tedu.common.ex.ServiceException;
import cn.tedu.common.pojo.po.UserStatePO;
import cn.tedu.passort.controller.UserController;
import cn.tedu.passort.dao.cache.ICodeCacheRepository;
import cn.tedu.passort.dao.cache.IUserCacheRepository;
import cn.tedu.passort.dao.persist.repository.IUserRepository;
import cn.tedu.passort.pojo.param.AddJobApplicantParam;
import cn.tedu.passort.pojo.param.AddRecruiterParam;
import cn.tedu.passort.pojo.param.RegParam;
import cn.tedu.passort.pojo.vo.UserLoginInfoVO;
import cn.tedu.passort.pojo.vo.UserLoginResultVO;
import cn.tedu.passort.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.TeaException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserRepository iUserRepository;
    @Autowired
    private ICodeCacheRepository iCodeCacheRepository;
    @Autowired
    private IUserCacheRepository iUserCacheRepository;
    @Override
    public void sendCode(String phone) {
        Random random = new Random();
        Integer code=0;
        while (code < 1000 || code > 9999) {
            code = random.nextInt(9000) + 1000;  // 生成4位随机数
        }
        String sendCode=code.toString();
        RegParam regParam=new RegParam();
        regParam.setPhone(phone);
        regParam.setCode(sendCode);
//        System.out.println(phone+"!!!!!!!!");
        iCodeCacheRepository.saveCode(regParam);
        HashMap map=new HashMap();
        map.put("code",sendCode);
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        com.aliyun.dysmsapi20170525.Client client = null;
        try {
            client = UserServiceImpl.createClient("LTAI5t7WncbrDv1t3qAmC6DY", "PzL336TbCUOuIpP6dKU1EjXK5WxfyX");
        } catch (Exception e) {
            e.printStackTrace();
        }
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam(JSON.toJSONString(map));
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
    @Override
    public UserLoginResultVO regAndLogin(RegParam regParam) {
        String code = iCodeCacheRepository.getCode(regParam.getPhone());
        if(regParam.getCode().equals(code)){
            int count = iUserRepository.count(regParam.getPhone());
            if(count==0){
                //注册
                    iUserRepository.reg(regParam.getPhone(), regParam.getRoleId());
            }
            //登录
            UserLoginInfoVO user = iUserRepository.getUser(regParam.getPhone());
            Long userId=iUserRepository.getIdByPhone(regParam.getPhone());
           Integer loginNum= user.getLoginNum();
           Long roleId= user.getRoleId();
            System.out.printf(loginNum+roleId+"");
           Integer isEnable=user.getIsEnable();
           if(regParam.getRoleId()!=roleId){
               throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"身份不正确");
           }
            if(loginNum==0){
//                return "第一次登录";


            }else {
                //用户是否被禁
                if(isEnable==0){
                    throw new ServiceException(ServiceCode.ERROR_UNAUTHORIZED_DISABLED,"被禁用");
                }
                //登录次数加一
                loginNum++;
                iUserRepository.updateLoginNum(regParam.getPhone(),loginNum);
            }
                List<String> permission=iUserRepository.getPermission(regParam.getPhone());
                //把查询到的权限列表转成json字符串
                String s = JSON.toJSONString(permission);
                //把字符串放在userStatePO对象中
                UserStatePO userStatePO=new UserStatePO();
                userStatePO.setAuthoritiesJsonString(s);
                userStatePO.setEnable(1);

                //写进redis中（hashmap）
                iUserCacheRepository.saveUserState(userId,userStatePO);

            //生成jwt
            String secretKey = "fkfFJKFsa$^#%Qs8j7&3F9^&*4I5*8()p97iURui43";
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", userId);
//            claims.put("username",user.getUsername());
//            claims.put("phone",regParam.getPhone());
//            claims.put("avatar",user.getAvatar());

            String jwt = Jwts.builder()
                    //header
                    .setHeaderParam("alg", "HS256")
                    .setHeaderParam("typ", "JWT")
                    //Payload
                    .setClaims(claims)
                    //Verify Signature
                    .signWith(SignatureAlgorithm.HS256, secretKey)
                    //完成
                    .compact();
            //返回数据和jwt
            UserLoginResultVO userLoginResultVO=new UserLoginResultVO();
            userLoginResultVO.setId(userId);
            userLoginResultVO.setPermission(permission);
            userLoginResultVO.setToken(jwt);
            userLoginResultVO.setRoleId(user.getRoleId());
            userLoginResultVO.setLoginNumber(loginNum);
            return userLoginResultVO;

        }else {
            throw new ServiceException(ServiceCode.ERROR_UNKNOWN,"验证码错误");
        }

    }

    @Override
    public void addJobApplicant(AddJobApplicantParam addJobApplicantParam) {

        iUserRepository.add(addJobApplicantParam);
    }

    @Override
    public void addRecruiter(AddRecruiterParam addRecruiterParam) {
        iUserRepository.add(addRecruiterParam);
    }

}
